package main

import (
	"fmt"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/360EntSecGroup-Skylar/excelize/v2"
)

var documentModes = []string{"Excel文档", "Word文档"}

// see: https://xuri.me/excelize/zh-hans/
func (f *MainForm) runExcel(dbIndex int32, tableNames, filePath string, callback func(log string)) {
	callback("开始生成Excel")
	file := excelize.NewFile()
	streamWriter, err := file.NewStreamWriter("Sheet1")
	if err != nil {
		fmt.Println(err)
		return
	}
	tableList := strings.Split(tableNames, separator)

	chooseTables := make([]table, 0)
	callback("获取表注释")
	err, tables := loadTables(DBConfig{
		DBHost:     dbConfigs[dbIndex].DBHost,
		DBName:     dbConfigs[dbIndex].DBName,
		DBUsername: dbConfigs[dbIndex].DBUsername,
		DBPassword: dbConfigs[dbIndex].DBPassword,
	})
	if err != nil {
		callback(err.Error())
	}

	for i := 0; i < len(tables); i++ {
		for j := 0; j < len(tableList); j++ {
			if tableList[j] == tables[i].TableName {
				chooseTables = append(chooseTables, tables[i])
			}
		}
	}

	rowId := 1

	tIndex := make([]string, len(tableList))
	hIndex := make([]string, len(tableList))
	bIndex := make([]int, len(tableList))

	for i, table := range chooseTables {
		callback("生成表[" + table.TableName + "]的字段信息开始")
		if len(table.TableName) == 0 {
			continue
		}
		fields := loadFields(table.TableName, DBConfig{
			DBHost:     dbConfigs[dbIndex].DBHost,
			DBName:     dbConfigs[dbIndex].DBName,
			DBUsername: dbConfigs[dbIndex].DBUsername,
			DBPassword: dbConfigs[dbIndex].DBPassword,
		})

		tIndex[i] = strconv.Itoa(rowId)
		_ = file.MergeCell("Sheet1", "A"+strconv.Itoa(rowId), "E"+strconv.Itoa(rowId))
		cell, _ := excelize.CoordinatesToCellName(1, rowId)
		title := ""
		if len(table.TableComment.String) > 0 {
			title = table.TableComment.String + ": " + table.TableName
		} else {
			title = table.TableName
		}
		_ = streamWriter.SetRow(cell, []interface{}{title})

		rowId++
		hIndex[i] = strconv.Itoa(rowId)
		header := []interface{}{"字段名", "字段类型", "是否为空", "默认值", "备注"}
		cell, _ = excelize.CoordinatesToCellName(1, rowId)
		if err := streamWriter.SetRow(cell, header); err != nil {
			fmt.Println(err)
		}

		rowId++
		for i := 0; i < len(fields); i++ {
			data := make([]interface{}, 5)
			data[0] = fields[i].ColumnName
			data[1] = fields[i].ColumnType
			data[2] = fields[i].IsNullable
			data[3] = fields[i].ColumnDefault.String
			data[4] = fields[i].ColumnComment
			cell, _ = excelize.CoordinatesToCellName(1, rowId)
			if err := streamWriter.SetRow(cell, data); err != nil {
				fmt.Println(err)
			}
			rowId++
		}
		rowId++
		bIndex[i] = rowId - 1
		callback("生成表[" + table.TableName + "]的字段信息完毕")
	}

	if err := streamWriter.Flush(); err != nil {
		fmt.Println(err)
	}

	filename := filepath.Join(filePath, dbConfigs[dbIndex].DBName+".xlsx")
	if err := file.SaveAs(filename); err != nil {
		fmt.Println(err)
	}
	callback("写入文件（无样式）")

	callback("重新打开文件[" + filename + "]，写入样式")
	file, err = excelize.OpenFile(filename)
	if err != nil {
		fmt.Println(err)
	}

	// 设置宽度
	callback("设置行宽度")
	if err := file.SetColWidth("Sheet1", "A", "D", 20.0); err != nil {
		fmt.Println(err)
	}
	if err := file.SetColWidth("Sheet1", "E", "E", 50.0); err != nil {
		fmt.Println(err)
	}

	// 设置边框
	callback("设置边框")
	border := []excelize.Border{
		{Type: "left", Color: "#000000", Style: 1},
		{Type: "right", Color: "#000000", Style: 1},
		{Type: "top", Color: "#000000", Style: 1},
		{Type: "bottom", Color: "#000000", Style: 1},
	}
	bStyle, _ := file.NewStyle(&excelize.Style{Border: border})
	for i := 0; i < len(bIndex); i++ {
		if i == 0 {
			_ = file.SetCellStyle("Sheet1", "A1", "E"+strconv.Itoa(bIndex[i]-1), bStyle)
		} else {
			_ = file.SetCellStyle("Sheet1", "A"+strconv.Itoa(bIndex[i-1]+1), "E"+strconv.Itoa(bIndex[i]), bStyle)
		}
	}

	// 设置表名样式
	callback("设置表名样式")
	tStyle, _ := file.NewStyle(&excelize.Style{
		Border:    border,
		Fill:      excelize.Fill{Type: "gradient", Color: []string{"#CCFCCC", "#CCFCCC"}},
		Font:      &excelize.Font{Bold: true},
		Alignment: &excelize.Alignment{Horizontal: "center"},
	})
	for i := 0; i < len(tIndex); i++ {
		_ = file.SetCellStyle("Sheet1", "A"+tIndex[i], "E"+tIndex[i], tStyle)
	}

	// 设置表头样式
	callback("设置表头样式")
	hStyle, _ := file.NewStyle(&excelize.Style{
		Border: border,
		Fill:   excelize.Fill{Type: "gradient", Color: []string{"#FFFF99", "#FFFF99"}},
		Font:   &excelize.Font{Bold: true},
	})
	for i := 0; i < len(hIndex); i++ {
		_ = file.SetCellStyle("Sheet1", "A"+hIndex[i], "E"+hIndex[i], hStyle)
	}

	callback("写入文件（完整版）")
	if err := file.SaveAs(filename); err != nil {
		fmt.Println(err)
	}
	callback("生成Excel完毕")
}
